package com.feihong.txgw.ui.activity.kaika;

import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.just.agentweb.AgentWeb;

import java.util.HashMap;

import butterknife.BindView;

/**
 * Created by Sabirjan on 2017/7/4.
 * TXGWApp.
 * 飞宏电子
 * 开卡步骤3  -----选择套餐
 */

public class KaiKaStep3Activity extends BaseActivity {

    @BindView(R.id.rel_contantframe)
    RelativeLayout webviewFrame;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mRequeryDataBtn;
    private String phoneNum = "";
    private String phoneNumID = "";
    private String iccid = "";
    private AgentWeb mAgentWeb;
    private AgentWeb.PreAgentWeb mPreAgentWeb;
    private Intent mTransIntent;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 10) {
                loadPage();
            }else if(msg.what == 11){
                mConnectErrorLayout.setVisibility(View.VISIBLE);
            }
        }
    };

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_kaika_step3;
    }

    @Override
    public void onDestroy() {
        try {
            webviewFrame.removeAllViews();
            if (mAgentWeb != null) {
                mAgentWeb.getWebLifeCycle().onDestroy();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        isAlRight = false;
        super.onPause();
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        KaikaManager.getmKaikaManager().addStack(this);
        mTransIntent = getIntent();
        phoneNum = mTransIntent.getStringExtra(KaiKaActivity.INTENT_PHOE_NUM);
        iccid = mTransIntent.getStringExtra(KaiKaActivity.INTENT_ICCID);
        phoneNumID = mTransIntent.getStringExtra(KaiKaActivity.INTENT_PHOE_NUM_ID);

        setPageTitle("选择套餐");
        setBackButtonFinish();
        mRequeryDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mConnectErrorLayout.setVisibility(View.GONE);
                refreshToken();
            }
        });
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webviewFrame, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout,R.id.agentweb_re_query_data_layout)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
                .ready();
    }

    //WebViewClient
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {


            return false;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

    };

    @Override
    protected void onResume() {
        if (mAgentWeb != null) {
            if(!isAlRight){
                mAgentWeb.getWebLifeCycle().onResume();
                isAlRight = ! isAlRight;
            }
        }
        super.onResume();

    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {


    };

    @Override
    public void bindData() {
        refreshToken();
    }

    private void loadPage(){
        //GET 参数列表
        HashMap<String, String> params = new HashMap<>();
        Log.i("wangzi", "loadPage: "+iccid+"  "+phoneNum+"  "+phoneNumID);
        String url = "";
        params.put("iccid", iccid);
        params.put("phonenum", phoneNum);
        params.put("phonenumid", phoneNumID);
        String getparams = new SignToken().setSigen(params);
        url = HttpTools.KAIKA_STEP3_WEBURL + "?" + getparams;
        LogUtils.i(TAG + ":持卡开户,选择套餐url:" + url);
        mAgentWeb = mPreAgentWeb.go(url);
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new Step3Interface(mAgentWeb, this, iccid, phoneNum));
        //水平不显示
        mAgentWeb.getWebCreator().getWebView().setHorizontalScrollBarEnabled(false);
        //垂直不显示
        mAgentWeb.getWebCreator().getWebView().setVerticalScrollBarEnabled(false);

        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        if (mAgentWeb != null) {
            isAlRight = true;
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }
    private boolean isAlRight = false;
    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void refreshToken() {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                Message message = Message.obtain();
                if (RefreshToken.getInstance().RetrofitRefreshTokenForGet()) {
                    message.what = 10;
                }else {
                    message.what = 11;
                }
                mHandler.sendMessage(message);
            }
        });
    }
}
